<?php

namespace app\controller\Api\V1\Client;

use app\helper\GetProductInfo;
use app\model\GameAuthorization;
use app\model\GameLoginNotice;
use app\model\ToolServer;
use app\request\Announcement;
use Exception;
use support\Request;
use support\Response;

class AnnouncementController
{

    protected GetProductInfo $getProductInfoRe;


    public function __construct()
    {
        $this->getProductInfoRe = GetProductInfo::getInstance();
    }


    /**
     * 登录公告
     *
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function Login(Request $request): Response
    {

        $validate = new Announcement();

        if (!$validate->scene('login')->check($request->all())) {
            throw new Exception($validate->getError(), 500);
        }

        $merchantInfo = $this->getProductInfoRe->GetMerchantPlatform();
        if ($request->input('release_type') == 1) {
            $product = $merchantInfo['ulid'];
            $user = $request->input('mch_id');

            $gameInfo = GameAuthorization::query()->where('ulid', $request->input('game_id'))
                ->where('merchant', $user)->first();
        } else {
            if (!empty($request->input('mch_id'))) {
                $product = $merchantInfo['ulid'];
                $user = $request->input('mch_id');
            } else {
                $developerInfo = $this->getProductInfoRe->GetDeveloperPlatform();
                $product = $developerInfo['ulid'];
                $user = $request->input('open_id');
            }

            $gameInfo = ToolServer::query()->where('ulid', $request->input('game_id'))->first();
        }

        $result = [];
        if ($gameInfo) {
            $gameInfo = $gameInfo->toArray();

            $notice = GameLoginNotice::query()->where('user_id', $user)->where('platform', $product)
                ->where('game_id', $gameInfo['ulid'])->where('state', 1)->oldest()->get();

            if (!empty($notice)) {
                foreach ($notice as $item) {
                    $result[] = [
                        'type' => $item['notice_type'],
                        'notice_title' => $item['notice_title'],
                        'page_title' => $item['page_title'],
                        'content' => $item['content'],
                    ];
                }
            }
        }

        return jsonRe($result);

    }

}